package com.lcz.mq.consumer;

import com.lcz.mq.consumer.bean.MailBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * 邮件发送业务逻辑类
 * Created by luchunzhou on 2018/3/12.
 */
@Component("mailBiz")
public class MailBiz {

    /**
     * spring配置中定义
     */
    @Autowired
    private JavaMailSender mailSender;
    /**
     * spring配置中定义
     */
    @Autowired
    private SimpleMailMessage simpleMailMessage;
    @Autowired
    private ThreadPoolTaskExecutor threadPool;

    /**
     * 发送模板邮件
     *
     * @param mailBean 需要设置四个参数：templateName,toMail,subject,mapModel
     * @throws Exception
     */
    public void mailSend(final MailBean mailBean) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    // 发送人,从配置文件中取得
                    simpleMailMessage.setFrom(simpleMailMessage.getFrom());
                    // 接收人
                    simpleMailMessage.setTo(mailBean.getTo());
                    simpleMailMessage.setSubject(mailBean.getSubject());
                    simpleMailMessage.setText(mailBean.getContent());
                    mailSender.send(simpleMailMessage);
                } catch (MailException e) {
                    throw e;
                }
            }
        });
    }
}
